import { cloneDeep, findIndex, uniqueId } from 'lodash'
import { getCurrentInstance, toRaw } from 'vue'
import {
  libDel,
  libRename,
  libMove,
  libDownLoadBatch,
  favoriteAddFile,
  libPicSetTag,
  libNewFolder,
  favoriteDelFile,
} from '@Config/server/api'
import { Messages, confirm } from '@Config/config'
import { message } from 'ant-design-vue'
import { useWin } from '@Hooks/win'
import ReName from '@Page/my/components/rename'
import Tags from '@Page/my/components/tag'
import FirendList from '@Page/my/components/firendsList'
import BatchTags from '@Page/my/components/tag/batch'
import { useRoute } from 'vue-router'
import RelationPath from '@Page/my/components/relationPath'
import FavoritePath from '@Page/favorites/components/favoritePath'
import { getOneFileType } from '@Config/const'

export const fileApi = () => {
  let route = useRoute()
  let { proxy } = getCurrentInstance()
  //改变文件状态
  let changeFileStatus = async (ids, dataStatus) => {
    //设置等待状态
    ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      proxy.tableData.data.source[_index].local_loading = true
      // proxy.tableData.data.source.splice(_index, 1)
    })

    let _r = await libDel({ ids: ids, ...dataStatus })
    //取消等待状态
    ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      proxy.tableData.data.source[_index].local_loading = false
    })

    if (_r.code == 0) {
      ids.map((x) => {
        let _index = findIndex(proxy.tableData.data.source, { id: x })
        proxy.tableData.data.source.splice(_index, 1)
      })

      Messages.add(message.success('操作成功'))
    } else {
      Messages.add(message.error(`操作失败[${_r.msg}]`))
    }
  }
  /**
   *
   * @param {*} _file Array  文件数据
   * @param {*} msg  //提示信息
   * @returns
   */
  let getFileNameAndTypeConfirm = (_file, msg) => {
    if (_file instanceof Array == false) {
      _file = [_file]
    }
    let _rs = _file.map((x) => {
      let _r = getOneFileType((xx) => xx.value == x.fileType)
      return { type: _r.label, name: x.name }
    })

    return {
      title: <span class="red">警告</span>,
      content: (
        <span>
          {msg}
          <b class="red">
            {_rs.map((x) => {
              return (
                <>
                  <span>[{x.type}]</span>
                  <span>[{x.name}]</span>
                </>
              )
            })}
          </b>
          吗?
        </span>
      ),
    }
  }
  /**
   * @description 删除文件夹
   * @param {*} e  单个文件的数据类型
   */
  let removeFile = async (e) => {
    await confirm(getFileNameAndTypeConfirm(e, '确定要删除'))
    changeFileStatus([e.id], { dataStatus: -100 })
  }

  /**
   * @description 单个文件恢复
   * @param {*} e  单个文件的数据类型
   */
  let recoveryFile = async (e) => {
    await confirm(getFileNameAndTypeConfirm(e, '确定要取消分享'))
    changeFileStatus([e.id], { dataStatus: 0 })
  }
  /**
   * @description 批量恢复
   * @param {*} e  单个文件的数据类型
   */
  let batchRecoveryFile = async (e) => {
    await confirm(getFileNameAndTypeConfirm(e, '确定要保存'))
    changeFileStatus(
      e.map((x) => x.id),
      { dataStatus: 0 }
    )
  }

  //批量删除
  let batchReoveFile = async () => {
    await confirm(
      getFileNameAndTypeConfirm(proxy.tables_selected, '确定要删除')
    )
    let ids = proxy.tables_selected.map((x) => x.id)
    changeFileStatus(ids, { dataStatus: -100 })
  }
  /**
   * @description 把文件夹移到回收站
   * @param {*} e 单个文件的数据类型
   * @returns null
   */
  let moveToTrash = async (e) => {
    await confirm(getFileNameAndTypeConfirm(e, '确定要删除'))
    changeFileStatus([e.id], { dataStatus: -1 })
  }
  //批量删除到回收站
  let batchToTrash = async () => {
    await confirm(
      getFileNameAndTypeConfirm(proxy.tables_selected, '确定要删除')
    )
    let ids = proxy.tables_selected.map((x) => x.id)
    changeFileStatus(ids, { dataStatus: -1 })
  }

  /**
   *
   * @descritpion 重命名文件弹出窗口
   */
  let [reNameWin] = useWin({
    component: (
      <ReName
        onResult={async ({ name, callBack }) => {
          let _r = await libRename({ id: reNameWin.target.id, name })
          if (_r.code == 0) {
            Messages.add(message.success('操作成功'))
            let _index = findIndex(proxy.tableData.data.source, {
              id: reNameWin.target.id,
            })
            proxy.tableData.data.source[_index].name = name
          } else {
            Messages.add(message.error(`操作失败[${_r.msg}]`))
          }
          callBack(_r)
        }}
      />
    ),
    attr: {
      title: '文件重命名',
    },
  })
  /**
   * @description 重命名文件
   * @param {*} e 文件数据
   */
  let reName = (e) => {
    reNameWin.target = e
    reNameWin({
      params: {
        info: e,
      },
    })
  }

  /**
   *
   * @description 改变文件或文件夹的位置
   * @param tTarget[]  移动到目标的对象 a->b= b
   * @param oTarget[]  需要移动的文件或文件夹a->b=a
   */
  let changePosition = async (tTarget, oTarget) => {
    oTarget.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x.id })
      proxy.tableData.data.source[_index].local_loading = true
    })

    let _r = await libMove({
      ids: oTarget.map((x) => x.id),
      pid: oTarget[0].pid,
      toId: tTarget.id,
    })

    oTarget.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x.id })
      proxy.tableData.data.source[_index].local_loading = false
    })
    if (_r.code == 0) {
      oTarget.map((x) => {
        let _index = findIndex(proxy.tableData.data.source, { id: x.id })
        proxy.tableData.data.source.splice(_index, 1)
      })
      Messages.add(message.success(`操作成功`))
    } else {
      Messages.add(message.error(`操作失败[${_r.msg}]`))
    }
  }
  /**
   *
   * @description 移动位置 弹出窗口
   */
  let [rePosWin] = useWin({
    component: (
      <RelationPath
        onResult={async ({ tTarget, oTarget }) => {
          await confirm(getFileNameAndTypeConfirm(oTarget, '确定要移动'))
          changePosition(tTarget, oTarget)
        }}
      />
    ),
    attr: {
      title: '选择位置',
    },
  })
  /**
   * @description 更改位置
   *
   */
  let [rePosWinUnPub] = useWin({
    component: (
      <RelationPath
        onResult={async ({ tTarget, oTarget }) => {
          rePosWinUnPub.callBack(tTarget, oTarget)
        }}
      />
    ),
    attr: {
      title: '选择位置',
    },
  })
  /**
   *
   * @param {*} e 移动文件的数据
   */
  let rePos = (e, isPublic) => {
    rePosWin({
      params: {
        target: [e],
        isPublic,
      },
    })
  }
  /**
   * @description 批量移动
   */

  let batchMove = (isPublic) => {
    let selected_obj = proxy.tables_selected
    rePosWin({
      params: {
        target: selected_obj,
        isPublic,
      },
    })
  }

  /**
   * @description  下载文件
   * @param objs []所需要下载的文件
   *
   */
  //下载
  let downLoad = async (objs) => {
    objs.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x.id })
      proxy.tableData.data.source[_index].local_loading = true
    })
    let _r = await libDownLoadBatch({ ids: objs.map((x) => x.id) })

    objs.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x.id })
      proxy.tableData.data.source[_index].local_loading = false
    })
    if (_r.code == 0) {
      Messages.add(message.success('下载成功'))
      location.href = _r.data
    } else {
      Messages.add(message.error(`下载失败[${_r.msg}]`))
    }
  }

  /**
   *
   * 备份文件
   */
  let createFavorite = async ({ favoriteId, ids }) => {
    ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      proxy.tableData.data.source[_index].local_loading = true
    })
    let _r = await favoriteAddFile({ ids, favoriteId })
    ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      proxy.tableData.data.source[_index].local_loading = false
    })
    if (_r.code == 0) {
      Messages.add(message.success('备份成功'))
    } else {
      Messages.add(message.error(`备份失败[${_r.msg}]`))
    }
  }

  /**
   *@description 取消备份
   * @param {*} fav_ids[] 取消备份的id
   */
  let cancelFavorite = async (fav_ids) => {
    let _op_ids2 = fav_ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      if (_index >= 0) {
        return proxy.tableData.data.source[_index]
      }
    })
    await confirm(getFileNameAndTypeConfirm(_op_ids2, '确定要取消备份'))

    let _op_ids = fav_ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      if (_index >= 0) {
        proxy.tableData.data.source[_index].local_loading = true
      }
      return proxy.tableData.data.source[_index].favoriteFile.id
    })

    let _r = await favoriteDelFile({ ids: _op_ids })
    fav_ids.map((x) => {
      let _index = findIndex(proxy.tableData.data.source, { id: x })
      if (_index >= 0) {
        proxy.tableData.data.source[_index].local_loading = false
      }
    })
    if (_r.code == 0) {
      //取消备份成功
      fav_ids.map((x) => {
        let _index = findIndex(proxy.tableData.data.source, { id: x })
        proxy.tableData.data.source.splice(_index, 1)
      })
    } else {
      Messages.add(message.error(`取消备份失败[${_r.msg}]`))
    }
  }

  //备份文件弹出窗口
  let [favWin] = useWin({
    component: (
      <FavoritePath
        onResult={({ favoriteId }) => {
          createFavorite({ favoriteId, ids: favWin.ids })
        }}
      />
    ),
    attr: {
      title: '备份',
    },
  })
  /**
   * @description 备份文件
   * @param {*} ids[] 备份文件
   */
  let favorite = (ids) => {
    favWin.ids = ids
    favWin({
      params: {
        libId: ids,
      },
    })
  }
  /**
   * @param {*} ids  加密文件的IDS集合
   */
  let unPublish = async (ids) => {
    await confirm(getFileNameAndTypeConfirm(ids, '确定要加密'))
    changeFileStatus(
      ids.map((x) => x.id),
      { isPublic: 0 }
    )
  }

  //拖动改变位置
  /**
   *
   * @param from 需要移动的文件
   * @param to 目标地
   */
  let reposByDrag = async ({ from, to }) => {
    if (to.fileType == 1) {
      Messages.add(message.error('目标地址只能是文件夹'))
    } else {
      let _r = getOneFileType((x) => x.value == from.fileType)
      let _r2 = getOneFileType((x) => x.value == to.fileType)
      await confirm({
        title: <span>提示</span>,
        content: (
          <span>
            确定要把
            <b class="red">
              [{_r.label}] [{from.name}]
            </b>
            移动到
            <b class="red">
              [{_r2.label}] [{to.name}]
            </b>
            吗？
          </span>
        ),
      })
      changePosition(to, [from])
    }
  }

  /**
   * 
   *@description  单个文件打标签
  
  */
  let [tagsWin] = useWin({
    component: (
      <Tags
        onResult={async ({ list, currentObject }) => {
          let _r = await libPicSetTag({ id: currentObject.id, tagIdList: list })
        }}
      />
    ),
  })

  /**
   *
   * @description批量打标签
   */
  let [batchTagsWin] = useWin({
    component: (
      <BatchTags
        onResult={async ({ list, currentObject }) => {
          // console.log(list, currentObject)
          // let _r = await libPicAddTag({ id: currentObject, tagIdList: list })
        }}
      />
    ),
  })
  /**
   *
   * @description 单个文件打标签
   * @param {*} x  FILE 对象
   */

  let singleFileTags = (x) => {
    tagsWin({
      params: {
        allList: [
          ...cloneDeep(
            proxy.tableData.data.source.filter((x) => x.fileType == 1)
          ),
        ],
        selected: [x], //当前选中的
        isTag: true,
      },
      attr2: {
        title: '打标签',
      },
    })
  }
  /**
   *
   * @param {*} x  文件
   * @description 文件详情
   */
  let fileThemes = (x) => {
    tagsWin({
      params: {
        allList: [
          ...cloneDeep(
            proxy.tableData.data.source.filter((x) => x.fileType == 1)
          ),
        ],
        selected: [x], //当前选中的
        isComment: true,
      },
      attr2: {
        title: '详情',
      },
    })
  }

  /**
   *
   * @param {*} selectedFiles 当前选中的文件
   * @param {*} imageFileType 当前目录下面所有的图片
   * @description 批量打标签
   */

  let batchFileTags = (selectedFiles, imageFileType) => {
    batchTagsWin({
      params: {
        allList: cloneDeep(imageFileType),
        // [
        //   ...cloneDeep(
        //     proxy.tableData.data.source.filter((x) => x.fileType == 1)
        //   ),
        // ],
        selected: selectedFiles, //当前选中的
      },
      attr2: {
        title: '批量打标签',
      },
    })
  }

  /**
   *
   * @description 创建文件夹
   */
  let createFolder = async () => {
    let lid = uniqueId('local_')
    proxy.tableData.data.source.push({
      fileType: 0,
      name: '等待创建',
      local_loading: true,
      id: lid,
    })
    let _r = await libNewFolder({
      id: route.query.id || 0,
      name: '新建文件夹' + lid.replace('local_', ''),
      isPublic: proxy.isPublic,
    })
    let _index = findIndex(proxy.tableData.data.source, { id: lid })
    if (_r.code == 0) {
      proxy.tableData.data.source.splice(_index, 1, { ..._r.data })
      Messages.add(message.success('创建文件夹成功'))
    } else {
      proxy.tableData.data.source.splice(_index, 1)
      Messages.add(message.error(`创建文件夹失败[${_r.msg}]`))
    }
  }

  /**
   *
   *@description 创建文件(上传图片)
   */
  let createFile = (e) => {
    if (e.file.status == 'done') {
      //上传完成。并且上传成功

      if (e.file.response.code == 0) {
        e.file.link.local_loading = false
        for (var prop in e.file.response.data) {
          e.file.link[prop] = e.file.response.data[prop]
        }
      } else {
        //上传失败

        Messages.add(message.error(`上传失败[${e.file.response.msg}]`))
        //上传失败删除等待框

        let _index = findIndex(proxy.tableData.data.source, {
          id: e.file.link.id,
        })
        proxy.tableData.data.source.splice(_index, 1)
      }
    }
  }
  /**
   * @description 上传文件前的回调
   * @param {*} file
   * @param {*} fileList
   */
  let beforeUploadFile = (file, fileList) => {
    //指向等待框
    file.link = {
      id: uniqueId('uploading_'),
      fileType: 1,
      local_loading: true,
    }
    proxy.tableData.data.source.push(file.link)
  }
  /**
   * @desc 发布
   * @param {*} x
   */
  let publish = async (x) => {
    rePosWinUnPub.callBack = async (tTarget, oTarget) => {
      await confirm(getFileNameAndTypeConfirm(x, '确定要取消加密'))
      changeFileStatus([x.id], {
        isPublic: 1,
        toId: tTarget.id,
      })
    }
    rePosWinUnPub({
      params: {
        isPublic: 1,
      },
    })
  }
  /**
   * 批量发布
   */
  let batchPublish = () => {
    rePosWinUnPub.callBack = async (tTarget, oTarget) => {
      await confirm(
        getFileNameAndTypeConfirm(proxy.tables_selected, '确定要取消加密')
      )
      changeFileStatus(
        proxy.tables_selected.map((x) => x.id),
        {
          isPublic: 1,
          toId: tTarget.id,
        }
      )
    }
    rePosWinUnPub({
      params: {
        isPublic: 1,
      },
    })
  }

  let [firendsWin] = useWin({
    component: <FirendList />,
    attr: {
      title: '分享文件',
    },
  })

  //分享给好友
  let shareToFriends = (e) => {
    console.log(e)
    firendsWin({})
  }

  return {
    removeFile,
    moveToTrash,
    reName,
    rePos,
    downLoad,
    favorite,
    unPublish,
    batchMove,
    rePosWin,
    batchReoveFile,
    batchToTrash,
    reposByDrag,
    singleFileTags,
    fileThemes,
    createFolder,
    batchFileTags,
    createFile,
    beforeUploadFile,
    publish,
    batchPublish,
    recoveryFile,
    batchRecoveryFile,
    cancelFavorite,
    shareToFriends,
  }
}
